﻿using System;
using System.Diagnostics;
using System.Security.Principal;

namespace System
{
    public class ProcessHelper
    {
        public static bool OpenFile(string filePath)
        {
            try
            {
                ProcessStartInfo psi = new ProcessStartInfo();
                //打开相应的软件

                psi.FileName = filePath;
                psi.CreateNoWindow = true;
                psi.UseShellExecute = true;
                psi.ErrorDialog = true;
                psi.Verb = "open";
                bool tryWithAdmin = false;
                Process ps;
                //try
                //{
                ps = Process.Start(psi);
                return true;
                //}
                //catch (Exception ex)
                //{

                //    //打开失败,尝试用管理员权限打开
                //    bool isAdmin =
                //        new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
                //    if (!isAdmin)
                //        tryWithAdmin = true;
                //}
                //if (tryWithAdmin)
                //{
                //    psi.UseShellExecute = true;
                //    psi.RedirectStandardError = false;
                //    psi.Verb = "runas;openas";
                //    ps = Process.Start(psi);
                //    return true;
                //}
            }
            catch (Exception ex)
            {
                GlobalManager.Logger.Log(ex);
            }
            return false;
        }

        public static bool Start(string exePath)
        {
            try
            {
                ProcessStartInfo psi = new ProcessStartInfo();
                //打开相应的软件

                psi.FileName = exePath;
                psi.CreateNoWindow = true;
                psi.UseShellExecute = true;
                psi.ErrorDialog = true;
                bool tryWithAdmin = false;
                Process ps;
                try
                {
                    ps = Process.Start(psi);
                    return true;
                }
                catch
                {

                    //打开失败,尝试用管理员权限打开
                    bool isAdmin =
                        new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
                    if (!isAdmin)
                        tryWithAdmin = true;
                }
                if (tryWithAdmin)
                {
                    psi.Verb = "runas";
                    ps = Process.Start(psi);
                    return true;
                }
            }
            catch (Exception ex)
            {
                GlobalManager.Logger.Log(ex);
            }
            return false;
        }
    }
}
